package com.inventive.system.monitoring.server.service.publisher;

import com.hazelcast.core.HazelcastInstance;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Required;

import java.util.HashSet;
import java.util.Set;

/**
 * User: grant
 */
public class ExternalStatisticPublisherFactory implements FactoryBean<Set<ExternalStatisticPublisher>> {

    private static final Log log = LogFactory.getLog(ExternalStatisticPublisherFactory.class);

    private Set<ExternalStatisticPublisher> externalStatisticPublishers;

    private Set<ExternalConnector> externalConnectors;

    private HazelcastInstance hazelcastInstance;

    @Override
    public Set<ExternalStatisticPublisher> getObject() throws Exception {

        if (externalConnectors != null && externalConnectors.size() > 0) {
            log.error("Loading " + externalConnectors.size() + " connectors " + externalConnectors);
        } else {
            log.error("No external connectors are defined");
        }

        if (null == externalStatisticPublishers) {
            externalStatisticPublishers = new HashSet<ExternalStatisticPublisher>();
            for (ExternalConnector externalConnector : externalConnectors) {
                externalStatisticPublishers.add(new ExternalStatisticPublisher(externalConnector.getServiceUrl(), externalConnector.getMachineName(), externalConnector.getProcessName(), hazelcastInstance, externalConnector.getDescriptors()));
            }
            log.info("Adding statistic publishers to connectors " + externalStatisticPublishers);

        }


        return externalStatisticPublishers;
    }

    @Override
    public Class<?> getObjectType() {
        return Set.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Required
    public void setExternalConnectors(Set<ExternalConnector> externalConnectors) {
        this.externalConnectors = externalConnectors;
    }

    @Required
    public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
        this.hazelcastInstance = hazelcastInstance;
    }
}
